package com.freedy.concurrent.Monitors.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static com.freedy.concurrent.Monitors.Sleeper.sleep;

/**
 * 可打断
 * @author Freedy
 * @date 2021/4/22 20:17
 */

@Slf4j
public class Test2 {
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            try {
                log.info("尝试获取锁");
                lock.lockInterruptibly();
                log.info("获取锁");
                while (true) {
                    sleep(1);
                }
            } catch (InterruptedException e) {
                log.info("被打断");
                e.printStackTrace();
            } catch (Exception e) {
                if (e.getCause() instanceof InterruptedException) {
                    log.info("被打断");
                }
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });
        //lock.lock();
        t1.start();
        sleep(1);
        t1.interrupt();
    }
}
